package net.ikenway.springboot.demo.Service.Implement;

import net.ikenway.springboot.demo.Dao.AddressRepository;
import net.ikenway.springboot.demo.Model.Dto.AddressDto;
import net.ikenway.springboot.demo.Model.Entity.Address;
import net.ikenway.springboot.demo.Service.Interface.AddressServiceIntf;
import net.ikenway.springboot.demo.Utils.MapperUtil;
import net.ikenway.springboot.demo.Utils.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityNotFoundException;
import java.util.List;

/**
 * @author MasterKenway <zk@ikenway.net>
 * @Description
 * @date Created Date 12/19/2020
 */
@Service
public class AddressServiceImpl implements AddressServiceIntf {
    private final AddressRepository addressRepository;
    private final MapperUtil mapperUtil;

    @Autowired
    AddressServiceImpl(AddressRepository addressRepository, MapperUtil mapperUtil) {
        this.addressRepository = addressRepository;
        this.mapperUtil = mapperUtil;
    }

    @Override
    public List<AddressDto> findAll() throws Exception {
        return mapperUtil.mapList(addressRepository.findAllByUserUserId(SpringContextUtil.getCurrentUser().getUserId()), AddressDto.class);
    }

    @Override
    public AddressDto findById(Long addressId) throws Exception {
        return mapperUtil.map(addressRepository.findById(addressId), AddressDto.class);
    }

    @Override
    public AddressDto create(AddressDto addressDto) throws Exception {
        Address address = mapperUtil.map(addressDto, Address.class);
        address.setUser(SpringContextUtil.getCurrentUser());
        return mapperUtil.map(addressRepository.save(address), AddressDto.class);
    }

    @Override
    public void update(AddressDto addressDto) throws Exception {
        Address address = existOrNot(addressDto.getAddressId());
        if (!address.getUser().getUserId().equals(SpringContextUtil.getCurrentUser().getUserId())) throw new EntityNotFoundException();
        address = mapperUtil.map(addressDto, Address.class);
        address.setUser(SpringContextUtil.getCurrentUser());
        addressRepository.save(address);
    }

    @Override
    public void delete(List<Long> addressIds) throws Exception {
        for (Long addressId : addressIds) {
            Address address = existOrNot(addressId);
            if (!address.getUser().getUserId().equals(SpringContextUtil.getCurrentUser().getUserId()))
                throw new EntityNotFoundException();
            addressRepository.delete(address);
        }
    }

    @Override
    public Address existOrNot(Long addressId) throws Exception {
        return addressRepository.findById(addressId).orElseThrow(EntityNotFoundException::new);
    }
}
